package com.aaa.json;

import com.aaa.entity.Dept;
import com.aaa.entity.Orgnization;
import com.aaa.entity.PetrolStation;
import com.aaa.service.DeptService;
import com.aaa.service.PetrolStationService;
import com.aaa.util.JsonUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ：Teacher陈
 * @date ：Created in 2020/7/26 12:52
 * @description：json字符串转换成java对象，并插入到数据库
 * @modified By：
 * @version: 1.0
 */
@SpringBootTest
public class JsonFormatUtil {
    @Autowired
    private DeptService deptService;
    @Autowired
    private PetrolStationService petrolStationService;

    @Test
    public void saveDept() {
        try {
            List<Orgnization> orgnizationList = (List<Orgnization>) JsonUtil.fromJsonToObject("D:\\org.json");
            List<Dept> deptList = new ArrayList<>();
            List<PetrolStation> petrolStationList = new ArrayList<>();
            for (Orgnization orgnization : orgnizationList) {
                String parentId = orgnization.getAttributes().getParentorgid();
                if (parentId.equals("null") ||parentId==null) {
                    parentId="0";
                }
                if (orgnization.getId().length() < 6) {
                    //json数据中包含两种类型的数据，id长的是加油站信息，短的是政府部门信息
                    Dept dept = new Dept();
                    dept.setDeptId(Integer.parseInt(orgnization.getId()));
                    dept.setDeptName(orgnization.getText());
                    dept.setCreateBy("admin");
                    dept.setCreateTime(new Date());
                    System.out.println(orgnization.getId()+"||"+orgnization.getText());
                    dept.setParentId(Integer.parseInt(parentId));
                    //deptList.add(dept);
                    //保存政府信息
                    deptService.saveDept(dept);
                } else {
                    PetrolStation petrolStation = new PetrolStation();
                    petrolStation.setStationName(orgnization.getText());
                    petrolStation.setParentId(Integer.parseInt(parentId));
                    petrolStation.setCreateBy("admin");
                    petrolStation.setCreateTime(new Date());
                    petrolStationList.add(petrolStation);
                }

            }
            //批量保存加油站信息
            petrolStationService.insertBatch(petrolStationList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
